/*
Copyright 2009 Jeff Carnes

This file is part of Fluant.

Fluant is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

Fluant is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package com.amiasleep.fluant.flaPublisher;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import com.amiasleep.fluant.flaPublisher.io.SWFOutput;
import com.amiasleep.fluant.flaPublisher.io.parser.SWFParser;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class ProfileIO {
	
	
	public static void write(Profile profile, Writer writer) throws TemplateOutputException
	{
		try
		{
			Configuration cfg = new Configuration();
			cfg.setClassForTemplateLoading(ProfileIO.class, "/");
			Template template = cfg.getTemplate("publishProfile.ftl");
		
			Map<String,Object> root = new HashMap<String,Object>();
			root.put("profile", profile);
		
			template.process(root, writer);
			try
			{
				writer.flush();
			}
			finally
			{
				writer.close();
			}
			
		}
		catch(IOException iox)
		{
			throw new TemplateOutputException(iox);
		}
		catch(TemplateException tex)
		{
			throw new TemplateOutputException(tex);
		}
	}
	
	
	
	public static Profile read(File profile)
	{
		Profile retVal = new Profile();
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try
		{
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(profile);
			
			SWFOutput swf = SWFParser.fromXml(doc);
			retVal.setSwf(swf);
		}
		catch(Exception ex)
		{
			System.out.println(ex);
		}
		
		return retVal;
	}

}
